package com.jyh.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author jyh
 * @Date 2024/9/24 9:13
 * @Description 这是专门操作SqlSession的工具类
 */
public final class SqlSessionUtil {
    private SqlSessionUtil() {

    }

    public static SqlSessionFactory ssf ;
    static {
        try {
            // SqlSession ---> SqlSessionFactory ---> SqlSessionFactoryBuilder
            // 1. 获取生产SqlSessionFactory对象的工厂
            SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
            // 2. 获取SqlSessionFactory对象
            // 2.1 将核心配置文件封装成流对象
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
            // 2.2 生产SqlSessionFactory对象
            ssf = ssfb.build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 获取SqlSession对象
    public static SqlSession getSqlSession(){
        // 3. 获取SqlSession对象
        return  ssf.openSession();
    }
}
